package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.GaoDeApiUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    //配送范围
    static final Long RANGE = 5000L;

    @Resource(name = "orderMapper")
    OrderMapper orderMapper;
    @Resource(name = "addressBookMapper")
    AddressBookMapper addressBookMapper;
    @Resource(name = "shoppingCartMapper")
    ShoppingCartMapper shoppingCartMapper;
    @Resource(name = "userMapper")
    UserMapper userMapper;
    @Resource(name = "orderDetailMapper")
    OrderDetailMapper orderDetailMapper;
    @Resource(name = "weChatPayUtil")
    WeChatPayUtil weChatPayUtil;
    @Resource(name = "gaoDeApiUtil")
    GaoDeApiUtil gaoDeApiUtil;
    @Resource(name = "webSocketServer")
    WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO 下单信息DTO，包含订单的详细信息如地址簿ID等
     * @return OrderSubmitVO 订单提交后的视图对象，包含订单的基本信息
     * @throws AddressBookBusinessException  如果地址簿信息为空则抛出异常
     * @throws ShoppingCartBusinessException 如果购物车为空则抛出异常
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 检查用户地址簿信息是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        // 检查购物车是否为空
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList.isEmpty()) throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        // 创建订单并插入订单表
        Orders orders = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()))
                .status(Orders.PENDING_PAYMENT)
                .userId(BaseContext.getCurrentId())
                .orderTime(LocalDateTime.now())
                .payStatus(Orders.UN_PAID)
                .phone(addressBook.getPhone())
                .address(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDetail())
                .consignee(addressBook.getConsignee())
                .userName(userMapper.selUserById(BaseContext.getCurrentId()).getName())
                .build();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orderMapper.add(orders);

        // 批量插入订单详细信息到订单详细表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(shoppingCartData -> {
            OrderDetail orderDetail = OrderDetail.builder()
                    .name(shoppingCartData.getName())
                    .image(shoppingCartData.getImage())
                    .orderId(orders.getId())
                    .dishId(shoppingCartData.getDishId())
                    .setmealId(shoppingCartData.getSetmealId())
                    .dishFlavor(shoppingCartData.getDishFlavor())
                    .number(shoppingCartData.getNumber())
                    .amount(shoppingCartData.getAmount())
                    .build();
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.addList(orderDetailList);

        // 清空用户的购物车信息
        ShoppingCart cart = new ShoppingCart();
        cart.setUserId(BaseContext.getCurrentId());
        shoppingCartMapper.delShoppingCart(cart);

        // 构建并返回订单提交后的视图对象
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
    }

    //分页条件查询历史订单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders ordersBuild = Orders.builder()
                .userId(BaseContext.getCurrentId())
                .status(ordersPageQueryDTO.getStatus())
                .build();
        List<OrderVO> ordersList = orderMapper.list(ordersBuild);
        ordersList.forEach(orders -> {
            orders.setOrderDetailList(orderDetailMapper.selOrderDetailByOrderId(orders.getId()));
        });
        Page<OrderVO> listPage = (Page<OrderVO>) ordersList;
        return new PageResult(listPage.getTotal(), listPage.getResult());
    }

    //根据订单id查询订单详细
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVO selOrderDetailByOrderId(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        List<OrderVO> orderVOList = orderMapper.list(orders);
        OrderVO orderVO = orderVOList.get(0);
        orderVO.setOrderDetailList(orderDetailMapper.selOrderDetailByOrderId(orderVO.getId()));
        return orderVO;
    }

    //再来一单

    /**
     * 创建一个新的订单。
     * 该方法首先根据订单ID查询现有的订单信息，然后基于查询到的信息创建一个新的订单实例，
     * 更新订单的相关属性如订单时间、预计交付时间等，最后将新订单及其细节信息保存到数据库中。
     *
     * @param id 订单的唯一标识符，用于查询和更新订单信息。
     * @return 无返回值。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void oneMoreOrder(Long id) {
        // 初始化订单视图对象和订单对象
        OrderVO ordersVO = new OrderVO();
        Orders orders = new Orders();
        orders.setId(id); // 设置订单ID用于查询
        // 根据订单ID查询订单视图列表
        List<OrderVO> orderVOList = orderMapper.list(orders);
        // 从查询结果中获取第一个订单视图对象
        ordersVO = orderVOList.get(0);
        // 设置订单详情列表
        ordersVO.setOrderDetailList(orderDetailMapper.selOrderDetailByOrderId(id));
        // 将订单视图对象的属性复制到订单对象
        BeanUtils.copyProperties(ordersVO, orders);
        // 初始化新订单的属性
        orders.setId(null); // 重置ID以创建新订单
        orders.setOrderTime(LocalDateTime.now()); // 设置订单时间
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1)); // 设置预计交付时间
        orders.setNumber(String.valueOf(System.currentTimeMillis())); // 设置订单编号
        orders.setStatus(Orders.PENDING_PAYMENT); // 设置订单状态为待支付
        // 添加新订单到数据库
        orderMapper.add(orders);
        // 遍历并更新订单详情列表中的每个订单详情，设置新的订单ID并添加到数据库
        List<OrderDetail> orderDetailList = ordersVO.getOrderDetailList();
        orderDetailList.forEach(orderDetail -> {
            orderDetail.setId(null); // 重置订单详情ID以创建新的订单详情
            orderDetail.setOrderId(orders.getId()); // 设置新的订单ID
        });
        // 批量添加订单详情到数据库
        orderDetailMapper.addList(orderDetailList);
    }

    //取消订单
    @Override
    public void cancelOrder(Long id) {
        Orders orders = Orders.builder()
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .id(id)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {

        Orders order = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        AddressBook addressBook = addressBookMapper.getById(order.getAddressBookId());
        String destination = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        String userAddress = gaoDeApiUtil.getLatitudeAndLongitude(destination);
        Long distance = gaoDeApiUtil.getDistance("", userAddress);
        log.info("收货地址距离商家{}米", (distance));
        if (distance > RANGE) throw new Exception(MessageConstant.IT_S_TOO_FAR_TO_DELIVER);

        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selUserById(userId);


        //调用微信支付接口，生成预支付交易单
//    JSONObject jsonObject = weChatPayUtil.pay(
//        ordersPaymentDTO.getOrderNumber(), //商户订单号
//        new BigDecimal(0.01), //支付金额，单位 元
//        "苍穹外卖订单", //商品描述
//        user.getOpenid() //微信用户的openid
//    );
//
//    if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//  throw new OrderBusinessException("该订单已支付");
//    }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime checkOutTime = LocalDateTime.now();
        Orders orders = Orders.builder()
                .checkoutTime(LocalDateTime.now())
                .payStatus(OrderPaidStatus)
                .status(OrderStatus)
                .number(ordersPaymentDTO.getOrderNumber())
                .userId(userId)
                .payMethod(ordersPaymentDTO.getPayMethod())
                .build();
        orderMapper.update(orders);
        orders.setId(orderMapper.getByNumber(orders.getNumber()).getId());

        //给管理员端发来单提醒
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", 1); // 1 来新订单
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

    }

    //管理员取消订单
    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancelDTO.getCancelReason())
                .build();
        orderMapper.update(orders);
    }

    //订单搜索
    @Override
    public PageResult selAllOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOList = orderMapper.selAllOrders(ordersPageQueryDTO);
        Page<OrderVO> orderVOPage = (Page<OrderVO>) orderVOList;
        return new PageResult(orderVOPage.getTotal(), orderVOPage.getResult());
    }

    //各个状态的订单数量统计
    @Override
    public OrderStatisticsVO selOrderStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        HashMap map = new HashMap();
        map.put("status", Long.valueOf(Orders.CONFIRMED));
        map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
        map.put("end", LocalDateTime.now().with(LocalTime.MAX));
        orderStatisticsVO.setConfirmed(orderMapper.selOrderStatistics(map));
        map.put("status",Long.valueOf(Orders.DELIVERY_IN_PROGRESS));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selOrderStatistics(map));
        map.put("status", Long.valueOf(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.selOrderStatistics(map));
        return orderStatisticsVO;
    }

    //接单
    @Override
    public void confirm(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    //拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = Orders.builder()
                .status(Orders.CANCELLED)
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build();
        orderMapper.update(orders);
    }

    //派送订单
    @Override
    public void delivery(Long id) {
        Orders orders = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(id)
                .build();
        orderMapper.update(orders);
    }

    //完成订单
    @Override
    public void complete(Long id) {
        Orders orders = Orders.builder()
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .id(id)
                .build();
        orderMapper.update(orders);
    }


    //用户催单
    @Override
    public void reminderOrder(Long id) {
        HashMap map = new HashMap();
        Orders order = new Orders();
        order.setId(id);
        List<OrderVO> ordersList = orderMapper.list(order);
        order.setNumber(ordersList.get(0).getNumber());
        map.put("type", 2); // 2 催单
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + order.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }


}
